package com.chuji.crmcj.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.MagSendNoticeDetailsActivity;
import com.chuji.crmcj.bean.MagNoticeInfo;
import com.chuji.crmcj.bean.SureCheckMessageInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.jauker.widget.BadgeView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MagReceiveNoticeFragment extends BaseFragment {
    /*通知布局*/
    private ListView lv_receive_notice;
    /*自定义适配器*/
    private CustomReceiveNoticeClientAdapter customReceiveNoticeClientAdapter;
    /*数据存储*/
    List<MagNoticeInfo.ApiParamObjEntity> magNoticeData;
    /*网络数据*/
    private MagNoticeInfo magNoticeInfo;
    /*网络是否已读*/
    private SureCheckMessageInfo sureCheckMessageInfo;
    //用户ID
    String UserID;
    Intent intent;
    BadgeView badgeView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mag_receive_notice, container, false);
        lv_receive_notice = (ListView) view.findViewById(R.id.lv_receive_notice);
        initDa();
        //下拉刷新
//        lv_receive_notice.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            public void onRefresh(
//                    PullToRefreshBase<ListView> refreshView) {
//                initData();
//            }
//        });
        return view;
    }

    @Override
    public void initData() {

    }

    private void initDa() {
        //第一次
        if (magNoticeData == null) {
            magNoticeData = new ArrayList<MagNoticeInfo.ApiParamObjEntity>();
        }
        requestData();
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return null;
    }

    private void requestData() {
        //初始化Volley
        UserID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        String strURL = String.format(UrlUtils.MAG_NOTICE_FORM + "&UserID=" + UserID + "&isReceive=1");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                magNoticeInfo = JSON.parseObject(response, MagNoticeInfo.class);
                magNoticeData.addAll(magNoticeInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customReceiveNoticeClientAdapter == null) {
                            customReceiveNoticeClientAdapter = new CustomReceiveNoticeClientAdapter();
                            lv_receive_notice.setAdapter(customReceiveNoticeClientAdapter);
                        } else {
                            customReceiveNoticeClientAdapter.notifyDataSetChanged();
                        }
                        //给ListView设置点击事件
                        lv_receive_notice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                Intent intent = new Intent(UIUtils.getContext(), MagSendNoticeDetailsActivity.class);
                                intent.putExtra("MessageID", magNoticeData.get(position).getMessageID());
                                if(magNoticeData.get(position).getIsRead().equals("0")) {
                                    uploadIsRead(magNoticeData.get(position).getMessageID());
                                }
                                System.out.println(magNoticeData.get(position).getMessageID() + "------------------------------------");
                                startActivity(intent);
                            }
                        });
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }

    public void uploadIsRead(String ID) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ID", ID);
        postRequest(UrlUtils.SUBMIT_SALES_ISREAD, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("消息已读");
            }
        });
    }

    /**
     * 自定义适配器
     */
    class CustomReceiveNoticeClientAdapter extends BaseAdapter {

        private Context context;

        @Override
        public int getCount() {
            return magNoticeData.size();
        }

        @Override
        public Object getItem(int i) {
            return magNoticeData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_notice, null);
                //初始化组件
                viewHolder.mLl_image_view = (FrameLayout) convertView.findViewById(R.id.ll_image_view);
                viewHolder.iv_tag = (ImageView) convertView.findViewById(R.id.iv_tag);
                viewHolder.mIv_client_image = (com.chuji.crmcj.view.CircleImageView) convertView.findViewById(R.id.iv_client_image);
                viewHolder.mTv_notice_title = (TextView) convertView.findViewById(R.id.tv_notice_title);
                viewHolder.mTv_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.mTv_post = (TextView) convertView.findViewById(R.id.tv_post);
                viewHolder.mTv_notice_time = (TextView) convertView.findViewById(R.id.tv_notice_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (magNoticeData.size() != 0) {
                viewHolder.mTv_notice_title.setText(magNoticeData.get(position).getTitle());
                viewHolder.mTv_name.setText(magNoticeData.get(position).getRealName());
                viewHolder.mTv_post.setText(magNoticeData.get(position).getPositionName());
                viewHolder.mTv_notice_time.setText(magNoticeData.get(position).getSendTime());
                if (magNoticeData.get(position).getAvatar() != null) {
                    Glide.with(UIUtils.getContext())
                            .load(UrlUtils.ImageIP + magNoticeData.get(position).getAvatar())
                            .into(viewHolder.mIv_client_image);
                } else {
                    viewHolder.mIv_client_image.setImageResource(R.drawable.morentouxiang);
                }
                if (magNoticeData.get(position).getIsRead() == "0") {
                    viewHolder.iv_tag.setVisibility(View.INVISIBLE);
                } else {
                    viewHolder.iv_tag.setVisibility(View.VISIBLE);
                }
            } else {
                UIUtils.showToastSafe("暂无数据");
            }
            return convertView;
        }
    }

    static class ViewHolder {
        private FrameLayout mLl_image_view;
        private com.chuji.crmcj.view.CircleImageView mIv_client_image;
        private TextView mTv_notice_title;
        private TextView mTv_name;
        private TextView mTv_post;
        private TextView mTv_notice_time;
        private ImageView iv_tag;
    }
}
